import moment from 'moment';

let readWaitingNodeId = ''; //节点名称id

/**
 * This handler retrieves the images from the clipboard as a base64 string and returns it in a callback.
 *
 * @param pasteEvent
 * @param callback
 */
export function retrieveImageFromClipboardAsBase64(pasteEvent, callback, imageFormat) {
	if (pasteEvent.clipboardData == false) {
		if (typeof callback == 'function') {
			callback(undefined);
		}
	}

	var items = pasteEvent.clipboardData.items;

	if (items == undefined) {
		if (typeof callback == 'function') {
			callback(undefined);
		}
	}

	for (var i = 0; i < items.length; i++) {
		// Skip content if not image
		if (items[i].type.indexOf('image') == -1) continue;
		// Retrieve image on clipboard as blob
		var blob = items[i].getAsFile();

		// Create an abstract canvas and get context
		var mycanvas = document.createElement('canvas');
		var ctx = mycanvas.getContext('2d');

		// Create an image
		var img = new Image();

		// Once the image loads, render the img on the canvas
		img.onload = function() {
			// Update dimensions of the canvas with the dimensions of the image
			mycanvas.width = this.width;
			mycanvas.height = this.height;

			// Draw the image
			ctx.drawImage(img, 0, 0);

			// Execute callback with the base64 URI of the image
			if (typeof callback == 'function') {
				callback(mycanvas.toDataURL(imageFormat || 'image/png'));
			}
		};

		// Crossbrowser support for URL
		var URLObj = window.URL || window.webkitURL;

		// Creates a DOMString containing a URL representing the object given in the parameter
		// namely the original Blob
		img.src = URLObj.createObjectURL(blob);
	}
}

/**
 *
 * @param {string} base64 base64 图片类型
 * @param {string} fileName 文件名
 * @returns { object } blob 对象
 */
export function base64ToFile(base64, fileName) {
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	var blob = new Blob([u8arr], {
		type: mime
	});
	blob.lastModifiedDate = new Date();
	blob.name = fileName;
	console.log('functionbase64ToFile -> blob', blob); // file
	return blob;
}

export function getBrowserClinetInfo() {
	var Sys = {};
	var ua = navigator.userAgent.toLowerCase();
	var re = /(msie|firefox|chrome|opera|version).*?([\d.]+)/;
	var m = ua.match(re);
	try {
		Sys.type = m[1].replace(/version/, 'safari');
		Sys.version = m[2];
	} catch (e) {
		Sys.type = 'unknown';
		Sys.version = 'unknown';
	}
	return Sys;
}

export function dataURItoBlob(dataURI) {
	//图片转成Buffer
	var byteString = atob(dataURI.split(',')[1]);
	var mimeString = dataURI
		.split(',')[0]
		.split(':')[1]
		.split(';')[0];
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], {
		type: mimeString
	});
}
/**
 * 替换模板字符串方法
 * @param {String} str 模板字符串数据
 * @param {Object} obj 需要替换的对象
 */
export function getSplitString(str, obj) {
	let s = str.split('{{');
	let needReplace = [];
	for (let index = 0; index < s.length; index++) {
		let element = s[index];
		if (element.indexOf('}}') > -1) {
			let ss = s[index].split('}}');
			needReplace.push({
				from: '{{' + ss[0] + '}}',
				to: obj[ss[0]] || '{{' + ss[0] + '}}'
			});
		}
	}
	for (let j = 0; j < needReplace.length; j++) {
		str = str.replace(needReplace[j].from, needReplace[j].to);
	}
	console.log(str);
	return str;
}

/** 2021-11-17 utils 新增节流方法 */

/**
 * 节流函数
 * @param { Function } callback 回调函数
 * @param { Number } time 等待时长
 * @returns
 */
export function throttle(callback, wait) {
	// 定义开始时间
	let start = 0;
	// 返回结果
	return function() {
		// 获取当前的时间戳
		let now = Date.now();
		if (now - start >= wait) {
			// 满足条件，执行回调函数
			callback.apply(this, arguments);
			start = now;
		}
	};
}

/**
 * 防抖函数
 * @param { Fucntion } callback  回调函数
 * @param {*} time 时长
 * @returns
 */
export function debounce(callback, time) {
	// 声明一个 timerId 用来存储定时器
	let timerId = null;
	return function() {
		// 判断 timerId 是否存在, 存在则清除
		if (timerId) {
			clearTimeout(timerId);
		}
		timerId = setTimeout(() => {
			callback.apply(this, arguments);
			// 重置定时器变量
			timerId = null;
		}, time);
	};
}

//分割字符串
//例:
//str: scanCode_1
//key:'_'
//originStr:scancode
//replaceStr:推送扫码
//return: 推送扫码1
export const subStringAndReplaceName = (str, key, originStr, replaceStr) => {
	if (!str) {
		return;
	}
	let index = str.indexOf(key);
	if (index !== -1) {
		let Number = str.substr(index + 1, str.length - index - 1);
		if (originStr === str.substr(0, index)) {
			return replaceStr + Number;
		}
		return str;
	}
	return str;
};

/**
 * 留痕会话中，坐席加入 / 离开会话的消息
 * @param { Object } user 用户数据
 * @returns { Object } 消息体
 */
export function userInSessionRecord(user) {
	let message = {};
	message.type = 'text';
	message.id = '';
	message.date = user.at;
	message.from = 'stytem';
	message.label = 'system';
	message.fromUser = {
		id: '',
		name: '系统消息',
		avatar: ''
	};
	message.data = `坐席 ${user.user.name} ${getUsertStatus(user.status)}`;
	return message;
}

export function systemSessionRecord(data) {
	let message = {};
	message.type = 'text';
	message.id = '';
	message.date = data.at;
	message.from = 'stytem';
	message.label = 'system';
	message.fromUser = {
		id: '',
		name: '系统消息',
		avatar: ''
	};
	message.data = `${getUsertName(data)} ${getUsertStatus(data.status)}`;
	return message;
}

export function formatSessionMessageRecords(records) {
	let map = new Map();
	let result = [];
	records.forEach(msg => {
		if (msg.msgType === 'peer-status' && msg.data.status === 'joined') {
			let user = { clientId: msg.data.id, role: msg.data.role, id: msg.data.user.id, userName: msg.data.user.name, isRobot: msg.data.user.profile.isRobot || false };
			map.set(msg.data.id, user);
		}
		if (msg.fromClientId === 'system') {
			let data = systemSessionRecord(msg.data);
			result.push(data);
		} else {
			if (msg.msgType === 'custom' || msg.msgType === 'peer-status' || msg.msgType === 'transfer' || msg.msgType === 'ai-action' || msg.msgType === 'invite' || msg.msgType === 'workflow-progress' || msg.msgType === '' || (msg.msgType === 'peer-cmd' && msg.data.cmd === 'face-recognition')) {
				return;
			}
			if (msg.msgType === 'peer-response') {
				if (msg.data.cmd === 'view' && !msg.data.data) {
					return;
				}

				if ((msg.data.cmd === 'fill-form' || msg.data.cmd === 'get-screenshot' || msg.data.cmd === 'get-handwriting') && (msg.data.status === 'in-progress' || msg.data.status === 'accepted')) {
					return;
				}
			}
			let data = filterClientMessage(msg, map);
			result.push(data);
		}
	});
	return result;
}

export function filterClientMessage(data, map) {
	let message = {};
	message.type = formatMessageType(data);
	message.id = data.fromClientId || '';
	message.date = data.createdAt || getCurrentDate();
	message.from = data.fromUserId || '';
	message.label = data.fromUserRole || '';
	message.fromUser = {
		id: data.fromUserId.id || '',
		name: data.fromUserName || '',
		avatar: data.fromUserAvatar || '',
		isRobot: map.get(data.fromClientId).isRobot
	};
	message.data = formatMessage(message.type, data, { role: message.label });
	return message;
}

/**
 *
 * @param { String } status 坐席状态
 * @returns
 */
export function getUsertStatus(status) {
	let result = '';
	switch (status) {
		case 'joined':
			result = '加入会话';
			break;
		case 'quit':
			result = '离开会话';
			break;
		default:
			result = '';
			break;
	}
	return result;
}

export function getUsertName(data) {
	let result = '';
	switch (data.role) {
		case 'agent':
			result = `坐席 ${data.user.name}`;
			break;
		case 'customer':
			result = `访客 ${data.user.name}`;
			break;
		default:
			result = '';
			break;
	}
	return result;
}

export function sendMessageToRecord(type, msg, user) {
	type = type ? type : 'text';
	let message = {};
	message.type = type;
	message.id = user.clientId || '';
	message.date = getCurrentDate();
	message.from = user.id;
	message.label = user.role;
	message.fromUser = {
		id: user.id,
		name: user.userName,
		avatar: user.picture || user.avatar,
		isRobot: user.isRobot || false
	};
	message.data = formatMessage(type, msg, user);
	return message;
}

/**
 * 筛选会话中坐席信息数据
 * @param { Array } members
 * @returns 筛选过后的坐席数组
 */
export function filterAgentMember(members) {
	let agentMembers = members
		.filter(item => item.role === 'agent')
		.map(agent => {
			return {
				date: agent.at,
				clientId: agent.id,
				role: agent.role,
				id: agent.user.id,
				userName: agent.user.name,
				org: agent.user.org,
				isRobot: agent.user.profile && agent.user.profile.isRobot ? agent.user.profile.isRobot : false,
				picture: agent.picture ? agent.picture : ''
			};
		});
	return agentMembers;
}
// 根据消息 from，筛选坐席信息
export function filterAgentByMsg(from, members) {
	let clients = members.map(client => {
		return {
			clientId: client.id,
			role: client.role,
			id: client.user.id,
			userName: client.user.name,
			org: client.user.org,
			isRobot: client.user.profile && client.user.profile.isRobot ? client.user.profile.isRobot : false,
			picture: client.user.profile.picture ? client.user.profile.picture : ''
		};
	});
	return clients.find(agent => agent.clientId === from);
}

/**
 *
 * @param { Date } sourceTime 源时间
 * @returns 新时间
 */
export function formatMessageTime(sourceTime) {
	let date = moment(sourceTime).format('yyyy/MM/DD');
	let time = moment(sourceTime).format('HH:mm:ss');
	let hour = new Date(sourceTime).getHours();
	let result = date + ' ' + (hour < 12 ? '上午' : '下午') + ' ' + time;
	return result;
}

/**
 * 格式化消息
 * @param { String } type 消息类型
 * @param { Object } msg 消息体
 * @returns 格式化后消息体
 */
export function formatMessage(type, msg, user) {
	console.log(msg);
	let result = '';
	switch (type) {
		case 'text':
			result = msg.text ? msg.text : msg.data ? (msg.data === 'silence-msg' ? '- -' : msg.data) : msg;
			break;
		case 'link':
			result = { type: msg.data.type, url: msg.data.url, name: msg.data.name, size: msg.data.size };
			break;
		default:
			result = formatBusinessMessage(type, msg, user);
			break;
	}
	return result;
}

/**
 * 格式化业务指令消息
 * @param { String } type 消息类型
 * @param { Object } msg 消息体
 * @returns 格式化后消息体
 */
export function formatBusinessMessage(type, msg, user) {
	let result = '';
	console.log(msg);
	let cmd = msg.cmd || msg.data.cmd;
	if (user.role === 'agent' && !msg.data.status) {
		switch (cmd) {
			case 'view':
				if (type === 'peer-cancel') {
					if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.nodeType && msg.data.data.type === 'messageSummary' && msg.data.data.nodeType === 'waitingReadNode') {
						result = { type: msg.data.type, contents: `超时未确认<${readWaitingNodeId}>汇总内容` };
					} else if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.nodeType && msg.data.data.type === 'scanCode' && msg.data.data.nodeType === 'waitingReadNode') {
						result = { type: msg.data.type, contents: `您超时未确认查阅<${readWaitingNodeId}>存储内容${msg.data.data.data.code}，已自动执行下一步操作` };
					} else {
						result = { type: msg.data.type, contents: `超时未查阅` };
					}
				} else if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.nodeType && msg.data.data.type === 'messageSummary' && msg.data.data.nodeType === 'waitingReadNode') {
					readWaitingNodeId = subStringAndReplaceName(msg.data.data.id, '_', 'messageSummary', '信息汇总');
					result = { type: msg.data.type, contents: `展示<${readWaitingNodeId}>汇总内容` };
				} else if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.nodeType && msg.data.data.type === 'messageSummary' && msg.data.data.nodeType === 'messageSummary') {
					result = { type: msg.data.type, contents: `发起信息汇总` };
				} else if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.nodeType && msg.data.data.type === 'scanCode' && msg.data.data.nodeType === 'waitingReadNode') {
					readWaitingNodeId = subStringAndReplaceName(msg.data.data.id, '_', 'scanCode', '推送扫码');
					result = { type: msg.data.type, contents: `展示<${readWaitingNodeId}>存储内容${msg.data.data.data.code}` };
				} else if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.type === 'richtext' && msg.data.data.data && msg.data.data.data.content) {
					result = { type: msg.data.data.type, content: msg.data.data.data.content }; //富文本
				} else {
					result = { type: msg.data.type || msg.type, url: msg.data.url || msg.data.data.url || msg.data.code || msg.data.data.code, fileName: msg.data.name || msg.data.data.name || msg.data.code || msg.data.data.code || '' };
				}
				break;
			case 'show-guide-box':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '取消引导框' : '推送引导框'}` };
				break;
			case 'get-screenshot':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '取消截图' : '请求截图'}` };
				break;
			case 'get-handwriting':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '取消签名' : '邀请签名'}` };
				break;
			case 'scan-code':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '取消扫码' : '请求扫码'}` };
				break;
			case 'get-geo-location':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '取消获取地理位置' : '请求获取地理位置'}` };
				break;
			case 'fill-form':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '终止推送表单' : '推送表单'}` };
				break;
			case 'confirm':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '取消汇总确认' : '推送汇总确认'}` };
				break;
			case 'make-choice':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '取消选项判断' : '推送选项判断'}` };
				break;
			case 'screen-share':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '取消屏幕共享' : '发起屏幕共享'}` };
				break;
			case 'screen-mark':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '取消共享标注' : '发起共享标注'}` };
				break;
			case 'screen-record':
				result = { type: cmd, contents: `${type === 'peer-cancel' ? '取消录屏' : '发起录屏'}` };
				break;
			case 'third-nlp':
				if (msg && msg.data && msg.data.data && msg.data.data.isStart) {
					result = { type: cmd, contents: `${type === 'peer-cancel' ? '' : '进行对接外部NLP'}` };
				} else {
					return;
				}
				break;
			default:
				result = msg;
				break;
		}
	} else {
		if (cmd === 'show-guide-box') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: msg.data.cmd, contents: `同意推送引导框` };
					break;
				case 'rejected':
					result = { type: msg.data.cmd, contents: `拒绝推送引导框` };
					break;
				case 'in-progress':
					result = { type: msg.data.cmd, contents: '' };
					break;
				case 'failed':
					result = { type: msg.data.cmd, contents: `推送引导框失败` };
					break;
				case 'done':
					result = { type: msg.data.cmd, contents: `` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (cmd === 'get-screenshot') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: cmd, contents: `同意截图` };
					break;
				case 'rejected':
					result = { type: cmd, contents: `拒绝截图` };
					break;
				case 'in-progress':
					result = { type: cmd, contents: '正在截图' };
					break;
				case 'failed':
					result = { type: cmd, contents: `截图失败` };
					break;
				case 'done':
					result = { type: 'pic', status: msg.data.status, url: msg.data.url || msg.data.data.url, fileName: msg.data.fileName || msg.data.name || msg.data.data.fileName || '' };
					break;
				default:
					result = msg;
					break;
			}
		} else if (cmd === 'get-handwriting') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: msg.data.cmd, contents: `同意签名` };
					break;
				case 'rejected':
					result = { type: msg.data.cmd, contents: `拒绝签名` };
					break;
				case 'in-progress':
					result = { type: msg.data.cmd, contents: '' };
					break;
				case 'failed':
					result = { type: msg.data.cmd, contents: `签名失败` };
					break;
				case 'done':
					result = { type: 'pic', status: msg.data.status, url: msg.data.url || msg.data.data.url, fileName: msg.data.fileName || msg.data.name || msg.data.data.fileName || '' };
					break;
				default:
					result = msg;
					break;
			}
		} else if (cmd === 'scan-code') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: cmd, contents: `同意扫码` };
					break;
				case 'rejected':
					result = { type: cmd, contents: `拒绝扫码` };
					break;
				case 'in-progress':
					result = { type: cmd, contents: '正在扫码' };
					break;
				case 'failed':
					result = { type: cmd, contents: `扫码失败` };
					break;
				case 'done':
					result = { type: cmd, status: msg.data.status, contents: `扫码成功，${msg.data.data.type === 'bar-code' ? '条形码：' : '二维码连接:'}${msg.data.data.code}` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (cmd === 'get-geo-location') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: cmd, contents: `同意获取地理位置` };
					break;
				case 'rejected':
					result = { type: cmd, contents: `拒绝获取地理位置` };
					break;
				case 'in-progress':
					result = { type: cmd, contents: '正在获取地理位置' };
					break;
				case 'failed':
					result = { type: cmd, contents: `获取地理位置失败` };
					break;
				case 'done':
					result = { type: cmd, status: msg.data.status, contents: `获取成功，${msg.data.data.address || ''}` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (cmd === 'fill-form') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: cmd, contents: `同意填写表单` };
					break;
				case 'rejected':
					result = { type: cmd, contents: `拒绝填写表单` };
					break;
				case 'in-progress':
					result = { type: cmd, contents: '正在填写表单' };
					break;
				case 'failed':
					result = { type: cmd, contents: `填写表单失败` };
					break;
				case 'done':
					result = { type: cmd, status: msg.data.status, contents: `提交表单 <${msg.data.data.formName}> 成功` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (cmd === 'confirm') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: cmd, contents: `同意汇总确认` };
					break;
				case 'rejected':
					result = { type: cmd, contents: `拒绝汇总确认` };
					break;
				case 'in-progress':
					result = { type: cmd, contents: '正在汇总确认' };
					break;
				case 'failed':
					result = { type: cmd, contents: `汇总确认失败` };
					break;
				case 'done':
					result = { type: cmd, contents: `汇总确认完成` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (cmd === 'make-choice') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: cmd, contents: `同意选项判断` };
					break;
				case 'rejected':
					result = { type: cmd, contents: `拒绝选项判断` };
					break;
				case 'in-progress':
					result = { type: cmd, contents: '正在选项判断' };
					break;
				case 'failed':
					result = { type: cmd, contents: `选项判断确认失败` };
					break;
				case 'done':
					result = { type: cmd, contents: `选项判断确认完成` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (msg.data.cmd === 'view' && msg.data.data.nodeType === 'waitingReadNode') {
			switch (msg.data.status) {
				case 'rejected':
					result = { type: msg.data.cmd, contents: `不确认<${readWaitingNodeId}>汇总内容` };
					break;
				case 'done':
					if (msg.data.data.type === 'messageSummary') {
						result = { type: msg.data.cmd, contents: `确认<${readWaitingNodeId}>汇总内容` };
					} else {
						result = { type: msg.data.cmd, contents: `已确认查阅<${readWaitingNodeId}>存储内容${msg.data.data.code}` };
					}
					break;
				default:
					break;
			}
		} else {
			console.log(cmd, msg);
		}
	}
	console.log(result);
	return result;
}

export function formatMessageType(data) {
	let type = '';
	switch (data.msgType) {
		case 'peer-response':
			type = data.data.cmd;
			break;
		case 'peer-cmd':
			type = data.data.cmd;
			break;
		default:
			type = data.msgType;
			break;
	}
	return type;
}
export function getCurrentDate() {
	return new Date();
}
